package encrypt

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"pan/common/exception"
)

func RsaEncrypt(origin string, pubKey string) (string, error) {
	if pubKey == "" {
		return "", exception.NewExpectError("public key must not be empty")
	}
	block, _ := pem.Decode([]byte(pubKey))
	key, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return "", err
	}
	bytes, err := rsa.EncryptPKCS1v15(rand.Reader, key.(*rsa.PublicKey), []byte(origin))
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(bytes), nil

}
